package cn.hsa.xxx.imgFsStore.service.Impl;

import cn.hsa.hsaf.core.fsstore.FSEntity;
import cn.hsa.hsaf.core.fsstore.FSManager;
import cn.hsa.xxx.imgFsStore.service.ImgStorageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Service
@Slf4j
public class ImgStorageServiceImpl implements ImgStorageService {

    @Autowired
    private FSManager fsManager;

    @Value("${fsstore.url}")
    private String url;

    @Value("${fsstore.bucket}")
    private String bucket;

    @Override
    public String uploadImgFile(MultipartFile file) {
        FSEntity fsEntity;
        try {
            InputStream fis = file.getInputStream();
            String fileName = file.getOriginalFilename();
            log.debug("文件名:{}", fileName);
            fsEntity = new FSEntity();
            fsEntity.setInputstream(fis);
            fsEntity.setName(fileName);
            fsEntity.setSize(fis.available());
            fsEntity.setContentType(FilenameUtils.getExtension(fileName));

            fsEntity = fsManager.putObject(bucket, fsEntity);


        } catch (Exception e) {
            log.error("Error", e);
            return "上传封面失败";
        }
        return fsEntity.getKeyId();
    }

    @Override
    public String getImgUrl(String keyId) {
        return (url + "/" + keyId);
    }

    @Override
    public String deleteImgFile(String keyId) {
        fsManager.deleteObject(bucket, keyId);
        return "删除成功";
    }


}
